<template>
  <div class="qrcode" ref="qrCodeUrl"></div>
</template>

<script>
import QRCode from 'qrcodejs2'

export default {
  props: {
    /* 地址的内容 */
    url: {
      type: String,
      required: true,
    },
    width: {
      type: Number,
      default: 124,
    },
    height: {
      type: Number,
      default: 124,
    },
    render: {
      type: String,
      default: 'canvas',
    },
    background: {
      type: String,
      default: '#f0f',
    },
    foreground: {
      type: String,
      default: '#ff0',
    },
  },
  mounted() {
    this.init()
  },
  methods: {
    //  生成二维码
    init() {
      new QRCode(this.$refs.qrCodeUrl, {
        width: this.width,
        height: this.height, // 高度
        text: this.url, // 二维码内容
        render: this.render, // 设置渲染方式（有两种方式 table和canvas，默认是canvas）
        background: this.background, // 背景色
        foreground: this.foreground, // 前景色
      })
    },
    downLoad(name) {
      //下载
      var canvasData = this.$refs.qrCodeUrl.getElementsByTagName('canvas')
      var a = document.createElement('a')
      var event = new MouseEvent('click') // 创建一个单击事件
      a.href = canvasData[0].toDataURL('image/png')
      a.download = name
      a.dispatchEvent(event) // 触发a的单击事件
    },
  },

  components: { QRCode },
}
</script>
<style lang="scss" scoped>
.qrcode {
  display: inline-block;
  padding: 10px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  box-sizing: border-box;
}
</style>